package com.dm.cloud.testclass;

import com.dm.cloud.excelpojo.TestExcelPojo;
import com.dm.cloud.utils.mingexcel.MingExcelUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

public class test1 {
    public static void main(String[] args) {

        List<String> usernames = Arrays.asList(new String[]{"测试","测试5", "测试3", "测试4", "测试1","测试1","测试6", "测试9", "测试2"});
        String username = "测试";
        System.out.println((calUsernameSuffix(usernames,username)));





    }

    private static String calUsernameSuffix(List<String> usernames, String originUsername){

        String username = originUsername;
        if(CollectionUtils.isNotEmpty(usernames)){
            if(usernames.contains(originUsername)){
                //列表中有重名 计算后缀
                List<Integer> suffixList = new ArrayList<>();
                for (String s : usernames) {
                    //截去前面的名字保留后面的数字部分
                    String suffix = s.substring(originUsername.length()).trim();
                    if(suffix.length()>0) {
                        try {
                            suffixList.add(Integer.valueOf(suffix));
                        } catch (Exception ex) {
                            System.out.println("ZHUAHNSHIABH ");
                        }
                    }
                }
                //排序
                suffixList.sort(Integer::compareTo);

                //获取未使用的后缀  包括空隙 1 2 ”3“ ”4“ 5 6 ”7“ ...
                Integer preSuffix = 0;
                for (Integer integer : suffixList) {
                    //与前一个后缀比较 正常是比前一个大一 大得多了就表示有空缺
                    if(integer.compareTo(preSuffix+1) > 0){
                        username = username + (preSuffix+1);
                        break;
                    }else{
                        preSuffix = integer;
                    }
                }
            }
        }
        return username;
    }
}
